package cn.itcast.system.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.system.dao.MenuRepository;
import cn.itcast.system.dao.PermissionRepository;
import cn.itcast.system.dao.RoleRepository;
import cn.itcast.system.service.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;
	
	@Autowired
	private PermissionRepository permissionRepository;
	@Autowired
	private MenuRepository menuRepository;
	@Override
	public List<Role> findByUser(User user) {
		if (user.getUsername().equals("admin")) {
			return roleRepository.findAll();
		} else {
			return roleRepository.findById(user.getId());
		}
	}
	@Override
	public List<Role> findAll() {
		return roleRepository.findAll();
	}
	@Override
	public void save(Role model, String[] permissionIds, String menuIds) {
		roleRepository.save(model);
		if (permissionIds != null) {
			for (String string : permissionIds) {
				Integer permissionId = Integer.parseInt(string);
				Permission permission = permissionRepository.findOne(permissionId);
				model.getPermissions().add(permission);
			}
		}
		if (menuIds != null) {
			String[] menustr = menuIds.split(",");
			for (String string : menustr) {
				Integer menuId = Integer.parseInt(string);
				Menu menu = menuRepository.findOne(menuId);
				model.getMenus().add(menu);
			}
		}
	}

}
